package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.User;
import cn.huhst.cas.weisiqian.service.UserExistException;
import cn.huhst.cas.weisiqian.service.UserService;
import cn.huhst.cas.weisiqian.util.JSON;
import cn.huhst.cas.weisiqian.util.Utils;

@WebServlet("/AddUser.do")
public class AddUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(AddUser.class);
	private UserService userservice = null;

	public AddUser() {
		super();
		userservice = new UserService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		JSON json = new JSON();
		HttpSession session = request.getSession();
		String logined = (String) session.getAttribute("logined");
		logger.debug("logined="+logined);
		if (logined != null && !"".equals(logined)) {
			int role = (Integer) session.getAttribute("role");
			if (role == 2) {
				
				String username = request.getParameter("username");
				String userpassword = request.getParameter("userpassword");
				String strrole = request.getParameter("role");
				logger.info("添加用户：用户名=" + username + " 用户密码=" + userpassword + " 用户角色=" + strrole);

				if (strrole != null && "".equals(strrole)) {
					json.put("status", "error");
					json.put("role", "用户名为空");
				} else {
					json = User.checkUserNameFormat(username, json);
					json = User.checkUserPasswordFormat(userpassword, json);
					json = User.checkRoleFormat(strrole, json);
					userpassword = Utils.encry(userpassword);
					if (json.isEmpty()) {
						User user = new User(username, userpassword, Integer.parseInt(strrole));
						boolean result = false;
						try {
							result = userservice.addUser(user);
							if (result) {
								json.put("status", "ok");
								logger.info("添加用户：" + user + "成功");
							} else {
								json.put("status", "error");
								json.put("msg", "添加用户失败");
							}
						} catch (UserExistException e) {
							json.put("status", "error");
							json.put("msg", "用户已存在");
						}
					} else {
						json.put("status", "error");
					}
				}
			} else {
				json.put("status", "error");
				json.put("msg", "没有权限添加用户");
			}
		} else {
			json.put("status", "error");
			json.put("msg", "用户未登录");
		}
		logger.info("JSON:" + json);
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
